package com.huarui.notice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.log4j.Logger;
import org.ewaf.framework.model.PagingInfo;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import com.huarui.employee.dao.IEmployeeDao;
import com.huarui.employee.model.Employee;
import com.huarui.notice.dao.INoticeDao;
import com.huarui.permission.service.PermissionService;
import com.huarui.user.security.UserHolder;

public class NoticeServiceImpl implements INoticeService {
	private Logger logger = Logger.getLogger(NoticeServiceImpl.class);
	private INoticeDao noticeDao;
	private NoticeDealerFactory noticeDealerFactory;
	private PlatformTransactionManager transactionManager;

	/*
	 * public void init(){
	 * 
	 * SessionMessage sm= new SessionMessage(); sm.setUserId(100);
	 * 
	 * UserHolder.setCurrenSessionMessage(sm);
	 * 
	 * Notice notice = new Notice(); notice.setUrl("http://localhost");
	 * notice.setContent("content"); notice.setDealed(true);
	 * notice.setNoticeType(Notice.NOTICE_TYPE_USER); notice.setReceiverId(1);
	 * notice.setReceiveType(Notice.RECEIVE_TYPE_USER);
	 * notice.setTitle("title");
	 * 
	 * create(notice);
	 * 
	 * 
	 * 
	 * }
	 */

	public INoticeDao getNoticeDao() {
		return noticeDao;
	}

	public void setNoticeDao(INoticeDao noticeDao) {
		this.noticeDao = noticeDao;
	}

	@Override
	public void create(Notice notice) {
		// TODO Auto-generated method stub
		notice.setSenderId(UserHolder.getCurrentSessionMessage().getUserId());
		noticeDao.create(notice);
	}

	@Override
	public Notice query(int noticeId) {
		return noticeDao.queryById(noticeId);
	}

	public Notice read(int id) {
		Notice notice = noticeDao.queryById(id);
		noticeDao.updateReaden(UserHolder.getCurrentSessionMessage()
				.getUserId().intValue(), new Integer[] { id }, true);
		notice.setReaden(true);
		return notice;
	}

	/*
	 * @Override public List<Notice> getNotices(int type, int receiverId) {
	 * return noticeDao.queryByReceiverId(type, receiverId); }
	 */

	@Override
	public boolean update(Notice notice) {
		return noticeDao.update(notice);
	}

	public boolean remove(Integer[] ids) {
		return noticeDao.delete(UserHolder.getCurrentSessionMessage()
				.getUserId().intValue(), ids);
	}

	public boolean deal(Integer[] ids, boolean dealed,
			Map<String, Object> resultHolder) {
		return noticeDao.updateDealed(UserHolder.getCurrentSessionMessage()
				.getUserId().intValue(), ids, dealed);
	}

	public boolean deal(Integer id, boolean dealed,
			Map<String, String[]> params, Map<String, Object> resultHolder) {

		Notice notice = noticeDao.queryById(id);
		NoticeDealer noticeDealer = noticeDealerFactory.getNoticeDealer(notice
				.getJsModuleId());
		if (noticeDealer == null) {
			logger.error("通知处理器未获取到，相关的jsModuleId: " + notice.getJsModuleId());
			return false;
		}
		boolean result = false;
		TransactionStatus status = transactionManager
				.getTransaction(new DefaultTransactionDefinition(
						TransactionDefinition.PROPAGATION_REQUIRED));
		try {
			result = noticeDealer.deal(notice, dealed, params, resultHolder);
			if (result) {
				noticeDao.updateDealed(UserHolder.getCurrentSessionMessage()
						.getUserId().intValue(), new Integer[] { id }, true);
			}
			transactionManager.commit(status);
		} catch (Throwable e) {
			transactionManager.rollback(status);
			logger.error("处理消息失败！", e);
			return false;
		}
		return result;
	}

	@Override
	public List<Notice> getMyReceivingNotices() {
		return noticeDao.queryByReceiverId(Notice.RECEIVE_TYPE_USER, UserHolder
				.getCurrentSessionMessage().getUserId().intValue());
	}

	@Override
	public List<Notice> getMySendingNotices() {
		// TODO Auto-generated method stub
		return noticeDao.queryBySenderId(UserHolder.getCurrentSessionMessage()
				.getUserId().intValue());
	}

	public void getPagingMyReceivingNotices(PagingInfo<Notice, Notice> paginInfo) {
		Notice condition = paginInfo.getCondition();
		condition.setReceiverId(UserHolder.getCurrentSessionMessage()
				.getUserId().intValue());
		// condition.setDealed(false);
		List<Notice> items = noticeDao.queryPagingNotices(condition, paginInfo
				.getSummary());
		int total = noticeDao.qqueryNoticeCount(condition);
		// logger.info("查询结果=="+items);
		paginInfo.setItems(items);
		paginInfo.setTotal(total);
	}

	public int getMyReceivingNoticeCount(int lastNoticeId) {
		Notice condition = new Notice();
		condition.setReceiverId(UserHolder.getCurrentSessionMessage()
				.getUserId().intValue());
		condition.setId(lastNoticeId);
		condition.setDealed(false);
		return noticeDao.qqueryNoticeCount(condition);
	}

	@Override
	public List<Notice> getMyCorpReceivingNotices() {
		// TODO Auto-generated method stub
		return noticeDao.queryByReceiverId(Notice.RECEIVE_TYPE_COMP, UserHolder
				.getCurrentSessionMessage().getCompanyId().intValue());
	}

	/*
	 * private EmployeeService employeeService;
	 * 
	 * public EmployeeService getEmployeeService() { return employeeService; }
	 * 
	 * public void setEmployeeService(EmployeeService employeeService) {
	 * this.employeeService = employeeService; }
	 */

	private IEmployeeDao employeeDao;

	private PermissionService permissionService;

	public PermissionService getPermissionService() {
		return permissionService;
	}

	public void setPermissionService(PermissionService permissionService) {
		this.permissionService = permissionService;
	}

	public IEmployeeDao getEmployeeDao() {
		return employeeDao;
	}

	public void setEmployeeDao(IEmployeeDao employeeDao) {
		this.employeeDao = employeeDao;
	}

	@Override
	@SuppressWarnings("unchecked")
	public void send(Notice notice, Integer permissionId) {
		
		if (notice.getReceiveType() == Notice.RECEIVE_TYPE_COMP) {
			Map map = new HashMap();
			map.put("companyId", notice.getReceiverId());
			map.put("isDelete", "0");
			List<Employee> employees = employeeDao.getEmployeeByCompanyId(map);
			// 分别给每个员工有权限的员工发送通知
			for (Employee employee : employees) {
				if (permissionService.hasPermission(employee.getId(),
						permissionId) == PermissionService.RESULT_HAS_PERMISSION) {
					Notice selfNotice = new Notice();
					selfNotice.setContent(notice.getContent());
					selfNotice.setDealed(false);
					selfNotice.setNoticeType(notice.getNoticeType());
					selfNotice.setReceiverId(employee.getUserId());
					selfNotice.setReceiveType(Notice.RECEIVE_TYPE_USER);
					selfNotice.setSenderId(notice.getSenderId());
					selfNotice.setTitle(notice.getTitle());
					selfNotice.setUrl(notice.getUrl());
					selfNotice.setJsModuleId(notice.getJsModuleId());
					selfNotice.setJsArgs(notice.getJsArgs());
					selfNotice.setUuid(UUID.randomUUID().toString());
					// 这里看看是否要加事务。。。
					this.noticeDao.create(selfNotice);
				}
			}
		} else {
			this.noticeDao.create(notice);
		}

	}

	public void setTransactionManager(
			PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	public void setNoticeDealerFactory(NoticeDealerFactory noticeDealerFactory) {
		this.noticeDealerFactory = noticeDealerFactory;
	}

}
